<?php

namespace app\api\controller;

use app\admin\model\Price;
use app\admin\model\Slide as SlideModel;
use app\admin\model\Goods;
use app\admin\model\Explosive as Explosive;
use app\admin\model\Overbalance as Overbalance;
use app\admin\model\Recommend as Recommend;
use app\common\controller\Api;
use app\common\library\Acsign;
use app\common\model\Authentication;
use GuzzleHttp\Client;
use think\Config;
use voku\helper\HtmlDomParser;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();

        $this->SlideModel = new SlideModel;
        $this->Goods = new Goods;
        $this->Explosive = new Explosive;
        $this->Overbalance = new Overbalance;
        $this->Recommend = new Recommend;
    }
    /**
     * 首页
     */
    public function index()
    {
        $limit = request()->param('limit',10);
        // 幻灯
        $slides = $this->SlideModel
            ->field('id,pic_image,title')
            ->where(['use_switch'=>1])
            ->order('id', 'desc')
            ->select();
        //爆品
        $explosive = $this->Explosive
            ->with(['good'])
            ->where('status','=',1)
            ->limit(6)
            ->order('createtime','desc')
            ->select();
        //超值
        $overbalance = $this->Overbalance
            ->with(['good'])
            ->where('status','=',1)
            ->limit(3)
            ->order('createtime','desc')
            ->select();
        //推荐
        $recommend = $this->Recommend
            ->with(['good'])
            ->where('status','=',1)
//            ->limit(3)
            ->order('createtime','desc')
            ->paginate($limit);
        $this->success('请求成功',[
            'slides'=>$slides,// 幻灯
            'explosive'=>$explosive,//爆品
            'overbalance'=>$overbalance,//超值
            'recommend'=>$recommend,//推荐
        ]);
    }

    /**
     * 配置说明
     * @return void
     */
    public function config()
    {
        $config['seller_commission'] = Config::get('site.seller_commission');
        $config['buyer_commission'] = Config::get('site.buyer_commission');
        $config['exposure_fee'] = Config::get('site.exposure_fee');
        $config['referral_fee'] = Config::get('site.referral_fee');
        $config['premium_fee'] = Config::get('site.premium_fee');
        $config['margin'] = Config::get('site.margin');
        $config['agreement'] = Config::get('site.agreement');
        $config['user_agreement'] = Config::get('site.user_agreement');
        $config['about_us'] = Config::get('site.about_us');
        $config['pay_agreement'] = Config::get('site.pay_agreement');
        $config['exposure_rule'] = Config::get('site.exposure_rule');
        $config['margin_statement'] = Config::get('site.margin_statement');
        $config['del_statement'] = Config::get('site.del_statement');
        $config['received_explain'] = Config::get('site.received_explain');
        $config['earnest'] = Config::get('site.earnest');//买家定金比例
        $config['sell_earnest'] = Config::get('site.sell_earnest');//卖家定金比例
        $config['max_nun'] = Config::get('site.max_nun');//预售或者求购数量上限
        $config['min_num'] = Config::get('site.min_num');//预售或者求购数量下限
        $config['driver'] = Config::get('site.driver');
        $config['transit_agreement'] = Config::get('site.transit_agreement');//委托暂存中转库协议
        $this->success('配置',$config);
    }

    /**
     * 鸡蛋价格
     */
    public function price()
    {
//        $list = Price::select();
        $list = db('price_log')
            ->where('day', '>=', date('Y-m-d', strtotime('-30 days')))
            ->select();
        $this->success('鸡蛋价格',[
            'list' => $list
        ]);
    }

    /**
     * 每日价格统计 0点10分统计
     */
    public function pricelog()
    {
        $price = Price::find();
//        foreach ($list as $v){
            $log = db('price_log')
                ->where('day',date('Y-m-d',time()))
                ->find();
            if($log){
                db('price_log')->where('id',$log['id'])->update([
                    'price' => $price['price'],
                    'pink_price' => $price['pink_price'],
                    'small_price' => $price['small_price']
                ]);
            }else{
                db('price_log')->insert([
                    'price' => $price['price'],
                    'pink_price' => $price['pink_price'],
                    'small_price' => $price['small_price'],
                    'day' => date('Y-m-d',time()),
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }
//        }
    }

    public function test()
    {
//        $userid = request()->param('uid');
//        $data = Authentication::where('user_id',$userid)->find();
//        $asignInstance = new Acsign();
//        $user = array();
//        $user["account"] = $data['serialNo'];//用户唯一识别码
////        $user["serialNo"] = time();
//        $user["name"] = $data['realName'];
//        $user["idCard"] = $data['idCardNo'];
//        $user["mobile"] = $data['mobile'];
//        $user["isNotice"] = 1;
//        $result = $asignInstance->addPersonalUserV2($user);
//        print_r($result);die;
//        $data = json_decode('{"uid":"5","bizId":"1717470287833","msg":"\u8ba4\u8bc1\u6210\u529f","result":"1","serialNo":"PA15020240604110447945194","sign":"r%2FShMD7J0wJqEeE%2BinVD5vnpJxnyInE9qUwYPLAbwSHq16BmyXOMN%2FWjhrG3PACtKxGv3wGazG2BzcDDdwpZFw%3D%3D","type":"\u4e2a\u4eba\u8fd0\u8425\u5546\u4e09\u8981\u7d20\u8ba4\u8bc1\u7f51\u9875\u7248"}');
//        dump($data);die;
        //上传待签署文件
        $contract = new \app\admin\model\Order();
        $contract->index(13);die;
//        $html = '<!DOCTYPE html><html><body><div class="content" id="css-selector">http://wwww.58655225.舞蹈服</div></body></html>';
//
//        $dom = HtmlDomParser::str_get_html($html);
// or
//        $dom = HtmlDomParser::file_get_html($file);

//        $element = $dom->findOne('#css-selector'); // "$element" === instance of "SimpleHtmlDomInterface"
//echo $element->nodeValue;
//        $elements = $dom->findMulti('.css-selector'); // "$elements" === instance of SimpleHtmlDomNodeInterface<int, SimpleHtmlDomInterface>
//
//        $elementOrFalse = $dom->findOneOrFalse('#css-selector'); // "$elementOrFalse" === instance of "SimpleHtmlDomInterface" or false
//
//        $elementsOrFalse = $dom->findMultiOrFalse('.css-selector'); // "$elementsOrFalse" === instance of SimpleHtmlDomNodeInterface<int, SimpleHtmlDomInterface> or false

//        $url='https://www.dianping.com/zhengzhou/ch10';
//        // 设置 headers
//        $headers = [
//            'Cookie: fspop=test; cy=160; cye=zhengzhou; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _lxsdk_cuid=18e383cf739c8-0d6d856a6803d8-26001b51-144000-18e383cf739c8; _lxsdk=18e383cf739c8-0d6d856a6803d8-26001b51-144000-18e383cf739c8; _hc.v=15aaa9c1-226a-6bf4-e60e-afb13bd4f98d.1710340503; Hm_lvt_602b80cf8079ae6591966cc70a3940e7=1710340504; s_ViewType=10; WEBDFPID=7u5861y12x7159uz0z8z9v2w2vv1w35u81v616w660097958474w6725-2025700517981-1710340517981QQSWSOOfd79fef3d01d5e9aadc18ccd4d0c95072342; qruuid=5c05aaef-12e4-476d-ac76-7394a55392e1; dper=02027e21eaf3cfbd181a6e6764523809b117fb0b75359f669f780a7c1482df4117f17669a174bdd5de731d41a1f929a78b24524c0643cd18deaa00000000a81e000081745f213bc7d018cf5a42c52d2cdc0eec72f7e37d36d9b9aaefa847964932c843057e1a72918327b27eb4569051634e; ll=7fd06e815b796be3df069dec7836c3df; Hm_lpvt_602b80cf8079ae6591966cc70a3940e7=1710340574; _lxsdk_s=18e383cf73a-97f-6d2-6f2%7C%7C40',
//            // 其他 headers 可以根据需要添加
//        ];
//        // 初始化 cURL
//        $ch = curl_init();
//        // 设置 cURL 选项
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//        // 执行 cURL 请求
//        $response = curl_exec($ch);
//        // 检查是否有错误发生
//        if (curl_errno($ch)) {
//            $error_msg = curl_error($ch);
//            echo "cURL Error: " . $error_msg;
//            curl_close($ch);
//            return;
//        }
//
//        // 关闭 cURL 资源
//        curl_close($ch);
//        // 使用 HtmlDomParser 解析 HTML
//        $html = HtmlDomParser::str_get_html($response);
//        // 提取 id 为 shop-all-list 下的 ul 里面的所有 li 里面的第一个 div 里面的 a标签链接
//        $links = [];
//        $shopAllList = $html->find('div#shop-all-list ul li div:first-child a', 0); // 假设每个 li 只有一个 div，并且我们取第一个
//        if ($shopAllList) {
//            foreach ($shopAllList->find('a') as $a) {
//                $links[] = $a->href;
//            }
//        }
//
//        // 输出提取到的链接
//        foreach ($links as $link) {
//            echo $link . '<br>';
//        }


        // 创建Guzzle客户端实例
        $client = new Client();

// 发送请求并获取响应内容
        $response = $client->request('GET', 'https://www.dianping.com/zhengzhou/ch10', [
            'headers' => [
                'Cookie' => 'fspop=test; cy=160; cye=zhengzhou; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _lxsdk_cuid=18e383cf739c8-0d6d856a6803d8-26001b51-144000-18e383cf739c8; _lxsdk=18e383cf739c8-0d6d856a6803d8-26001b51-144000-18e383cf739c8; _hc.v=15aaa9c1-226a-6bf4-e60e-afb13bd4f98d.1710340503; Hm_lvt_602b80cf8079ae6591966cc70a3940e7=1710340504; s_ViewType=10; WEBDFPID=7u5861y12x7159uz0z8z9v2w2vv1w35u81v616w660097958474w6725-2025700517981-1710340517981QQSWSOOfd79fef3d01d5e9aadc18ccd4d0c95072342; qruuid=5c05aaef-12e4-476d-ac76-7394a55392e1; dper=02027e21eaf3cfbd181a6e6764523809b117fb0b75359f669f780a7c1482df4117f17669a174bdd5de731d41a1f929a78b24524c0643cd18deaa00000000a81e000081745f213bc7d018cf5a42c52d2cdc0eec72f7e37d36d9b9aaefa847964932c843057e1a72918327b27eb4569051634e; ll=7fd06e815b796be3df069dec7836c3df; Hm_lpvt_602b80cf8079ae6591966cc70a3940e7=1710340574; _lxsdk_s=18e383cf73a-97f-6d2-6f2%7C%7C40', // 设置你的Cookie
            ],
        ]);

// 获取响应体内容
        $htmlContent = $response->getBody()->getContents();
        // 解析HTML内容
        $html = HtmlDomParser::str_get_html($htmlContent);

// 查找ID为shop-all-list的元素下的ul
        $ulElement = $html->find('div#shop-all-list ul', 0);

// 遍历ul下的所有li元素
        foreach ($ulElement->find('li') as $li) {
            // 查找每个li下的第一个div内的a标签
            $aElement = $li->find('div:first-child a', 0);

            if ($aElement) {
                // 提取a标签的href属性，即链接地址
                $link = $aElement->href;
                echo $link . PHP_EOL; // 输出链接或将其保存到数组中
            }
        }
    }
}
